﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Mvc;
using BSF.Enums;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using HuntingFishGame.ManageDomain.BLL.WeChat;

namespace HuntingFishGame.H5.Controllers
{
    public class MenuFormController : Controller
    {
        private readonly string access_token = WeixinConfig.BaseAccessToken(WeixinType.CertServiceAccount).ParamValue;
        // GET: MenuForm
        public ActionResult Index()
        {
            return View();
        }


        public ActionResult MenuOperation(string operation)
        {
            string result = string.Empty;
            switch (operation)
            {
                case "createMenu":
                    result = CreateMenu();
                    break;
                case "deleteMenu":
                    result = DeleteMenu();
                    break;
                case "selectMenu":
                    result = SelectMenu();
                    break;
            }
            if (!string.IsNullOrWhiteSpace(result))
            {
                return Json(new { code = (int)BSFAPICode.Success, msg = result, ReturnUrl = "" });
            }
            else
            {
                return Json(new { code = (int)BSFAPICode.NormalError, msg = "操作失败", ReturnUrl = "" });
            }
            //return GetPage(@"https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + access_token, "");//GetCode.Code
        }

        #region 给模板发送消息
        /// <summary>
        /// 给模板发送消息
        /// </summary>
        /// <param name="posturl"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public string GetPage(string posturl, string postData)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(postData);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                if (!string.IsNullOrEmpty(content))
                {
                    JObject jo = (JObject)JsonConvert.DeserializeObject(content);
                    //this.Label1.Text = content;
                    //40001:获取access_token时AppSecret错误，或者access_token无效
                    if (jo["errcode"] != null && (jo["errcode"].ToString() == "40001" || jo["errcode"].ToString() == "40014" || jo["errcode"].ToString() == "42001"))
                    {
                        ////重新获取access_token
                        //GetCode getCode = new GetCode();
                        //getCode.GetCodeValue();

                        //根据模板给微信账户发消息
                        string jsonText = System.IO.File.ReadAllText(Server.MapPath("~/Config/Menu.txt"));
                        GetPage("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + access_token, jsonText);//GetCode.Code
                    }
                }
                return content;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }
        }
        #endregion

        #region 删除菜单
        /// <summary>
        /// 删除菜单
        /// </summary>
        private string DeleteMenu()
        {
            string result = GetPage("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + access_token, "");//GetCode.Code
            Helper.ExtLog("删除菜单，时间：" + DateTime.Now);
            return result;
        }
        #endregion

        #region 创建菜单
        /// <summary>
        /// 创建菜单
        /// </summary>
        private string CreateMenu()
        {
            string result = string.Empty;
            byte[] byData = new byte[100];
            char[] charData = new char[1000];
            try
            {
                //FileStream file = new FileStream(Server.MapPath("~/Config/Menu.txt"), FileMode.Open);
                //file.Seek(0, SeekOrigin.Begin);
                //file.Read(byData, 0, 100); //byData传进来的字节数组,用以接受FileStream对象中的数据,第2个参数是字节数组中开始写入数据的位置,它通常是0,表示从数组的开端文件中向数组写数据,最后一个参数规定从文件读多少字符.
                //Decoder d = Encoding.Default.GetDecoder();
                //string bb =d.ToJson();//(byData, 0, byData.Length, charData, 0);
                //直接读取出字符串
                string jsonText = System.IO.File.ReadAllText(Server.MapPath("~/Config/Menu.txt"));
                result = GetPage("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + access_token, jsonText);//GetCode.Code
                //file.Close();
            }
            catch (IOException e)
            {
                throw e;
            }

            Helper.ExtLog("创建菜单，时间：" + DateTime.Now);
            return result;
        }
        #endregion

        #region 查询菜单
        /// <summary>
        /// 查询菜单
        /// </summary>
        private string SelectMenu()
        {
            string result = string.Empty;
            //string jsonText = System.IO.File.ReadAllText(Server.MapPath("~/Config/Menu.txt"));
            result = GetPage("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" + access_token, "");//GetCode.Code
            Helper.ExtLog("查询菜单，时间：" + DateTime.Now);
            return result;
        }
        #endregion
    }
}